<?php

namespace app\controllers;

use app\common\components\BaseWebController;
use app\common\services\applog\AppLogService;
use yii\log\FileTarget;
use Yii;

class ErrorController extends BaseWebController
{
   public function actionError()
   {
       //记录错误信息到文件和数据库
       $error = Yii::$app->errorHandler->exception;
       $err_msg = '';
       if ($error) {
           $file = $error->getFile();
           $line = $error->getLine();
           $message = $error->getMessage();
           $code = $error->getCode();

           $log = new FileTarget();
           $log->logFile = Yii::$app->getRuntimePath(). "/logs/err.log";

           $err_msg = $message ." [file:{$file}][line:{$line}][code:{$code}][url:{$_SERVER['REQUEST_URI']}][POST_DATA:". http_build_query($_POST). "]";
           $log->messages[] = [
               $err_msg,//错误信息
               1,//错误级别
               'application',//应用名称
               microtime(true)//错误时间
           ];

           $log->export();
           //todo 写入到数据库中
            AppLogService::addErrorLog(\Yii::$app->id, $err_msg);
       }
       return $this->render('error', [
           'error' => $err_msg,
       ]);
   }
}
